/**
 * @desc 将可以选择的日期的列表构造成日历
 * step1: 分别根据列表中第一个和最后一个日期,日期所在的月份
 * step2: 计算出所在月份一共有多少天,并生成相应的空日期数组(dateArr)
 * step3: 将空日期数组和可选日期数组合并成新数组(concatArr)
 * step4: 将concatArr按照月份拆分为多个数组,并得到finalArr
 */

import { dateFormate } from '@/utils'

export default function getFinalDateList(markDateList) {
  if (!markDateList.length) {
    return []
  }

  let startDate = new Date(markDateList[0].thatDate)
  let endDate = new Date(markDateList[markDateList.length - 1].thatDate)
  startDate = new Date(startDate.getFullYear(), startDate.getMonth(), 1)
  endDate = new Date(endDate.getFullYear(), endDate.getMonth() + 1, 0)
  const dayLength = (endDate - startDate) / (1000 * 60 * 60 * 24) + 1
  const dateArr = []
  const y = startDate.getFullYear()
  const m = startDate.getMonth()
  const d = startDate.getDate()

  for (let i = 0; i < dayLength; i++) {
    const currDate = dateFormate(new Date(y, m, d + i), 'yyy-mmm-ddd')
    dateArr.push({ date: currDate })
  }

  const concatArr = dateArr.map(v => ({
    ...v,
    ...markDateList.find(o => o.thatDate === v.date)
  }))

  const finalArr = []
  concatArr.forEach((v, i) => {
    if (!finalArr.length) {
      finalArr.push([v])
    } else {
      const last = finalArr[finalArr.length - 1][0]
      const y1 = new Date(last.date).getFullYear()
      const y2 = new Date(v.date).getFullYear()
      const m1 = new Date(last.date).getMonth()
      const m2 = new Date(v.date).getMonth()
      if (y1 === y2 && m1 === m2) {
        finalArr[finalArr.length - 1].push(v)
      } else {
        finalArr.push([v])
      }
    }
  })
  return finalArr
}
